package com.example.service.impl;

import com.example.entity.MessageNotice;
import com.example.entity.authority.Party;
import com.example.entity.paperlessMaintance.PaperlessMaintanceApply;
import com.example.entity.training.TrainingPlan;
import com.example.ext.entity.ExtElevator;
import com.example.ext.entity.ExtParty;
import com.example.mapp.*;
import com.example.service.PaperlessMaintService;
import com.example.util.DateUtils;
import com.example.util.ResultUtil;
import com.example.util.StringUtil;
import com.example.util.XmlFill;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class PaperlessMaintServiceImpl implements PaperlessMaintService {

    private static final Logger logger = LoggerFactory.getLogger(PaperlessMaintServiceImpl.class);

    @Autowired
    PaperlessMaintMapp paperlessMaintMapp;

    @Autowired
    private PartyMapp partyMapp;

    @Autowired
    private MessageNoticeMapp messageNoticeMapp;

    @Autowired
    private SysUserMapp userMapp;

    @Autowired
    private PartyCheckMapp partyCheckMapp;

    @Autowired
    private Environment environment;

    @Autowired
    private PartyUserMapp partyUserMapp;

    @Autowired
    private SysUserRoleMapp sysUserRoleMapp;

    @Autowired
    private ElevatorMapp elevatorMapp;




    @Override
    public Map<String, Object> query(PaperlessMaintanceApply paperlessMaintanceApply) {
        Map<String,Object> resultMap = new HashMap<>();
        try{
            if((paperlessMaintanceApply.getCurrentPage()) != null && paperlessMaintanceApply.getPageSize() != null){
                Page<TrainingPlan> page = PageHelper.startPage(paperlessMaintanceApply.getCurrentPage(),paperlessMaintanceApply.getPageSize());
                List<PaperlessMaintanceApply> list = paperlessMaintMapp.query(paperlessMaintanceApply);
                resultMap.put("list",list);
                resultMap.put("total",page.getTotal());
            }else{
                List<PaperlessMaintanceApply> list = paperlessMaintMapp.query(paperlessMaintanceApply);
                resultMap.put("list",list);
            }
        }catch (Exception e){
            logger.error(e.getMessage());
            return ResultUtil.returnError(e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("成功",resultMap);
    }

    @Override
    @Transactional
    public Map<String, Object> add(PaperlessMaintanceApply paperlessApply) {
        try{
            paperlessApply.setApplyDate(DateUtils.getDate("yyyy-MM-dd"));
            paperlessMaintMapp.insert(paperlessApply);
            return ResultUtil.returnSuccess("添加成功", null);
        }catch (Exception e){
            logger.error("无纸化维保申请记录添加失败！",e);
            return ResultUtil.returnError("新增失败",null);
        }
    }

    /**
     * 对无纸化维保申请进行审批
     * @param paperlessApply
     * @return
     */
    @Override
    @Transactional
    public Map<String, Object> update(PaperlessMaintanceApply paperlessApply) {
        try {
            paperlessMaintMapp.update(paperlessApply);
            String title = null;
            String content = null;
            List<String> users = null;
            Map<String, Object> map = new HashMap<>();
            map.put("roleName", "%管理人员%");
            //向区级监管部门，提交申请发送消息通知
            if ("1".equals(paperlessApply.getApplyStatus())) {
                title = "无纸化维保申请";
                content = "您有一份无纸化维保试点申请，需要您审批，请及时确认处理！";
                //获取无纸化申请中电梯
                map.put("partyId", paperlessApply.getJgPartyId());
            }else if("2".equals(paperlessApply.getApplyStatus())){
                //中止理由不为空时
                if(StringUtils.isNotEmpty(paperlessApply.getSuspendReason())){
                    title = "无纸化维保中止审批";
                    content = "您提交的无纸化维保试点申请，审批未通过，请及时确认处理！";
                    map.put("partyId", paperlessApply.getJgPartyId());
                }else{
                    title = "无纸化维保审批";
                    content = "您提交的无纸化维保试点申请，已审批通过，请及时确认处理！";
                    map.put("partyId", paperlessApply.getMaintenancePartyId());
                }
                /**
                 * 添加电梯参加无纸化维保标识
                 */
                Map<String,String> params = new HashMap<>();
                params.put("elevatorIds",paperlessApply.getElevatorIds());
                params.put("isPaperlessMaintenance","1");
                elevatorMapp.updatePaperLessElevators(params);
            }else if("3".equals(paperlessApply.getApplyStatus())){
                title = "无纸化维保审批";
                content = "您提交的无纸化维保试点申请，已审批拒绝，请及时确认处理！";
                map.put("partyId", paperlessApply.getMaintenancePartyId());
            }else if("4".equals(paperlessApply.getApplyStatus())){
                title = "无纸化维保中止申请";
                content = "您有一份无纸化维保试点中止申请，需要您审批，请及时处理";
                map.put("partyId", paperlessApply.getParentParentPartyId());
            }else if("5".equals(paperlessApply.getApplyStatus())){
                map.put("partyId", paperlessApply.getJgPartyId());
                title = "无纸化维保中止审批";
                content = "您提交的无纸化维保试点中止申请，已审批通过，请及时处理";
                /**
                 * 添加电梯参加无纸化维保标识（未参与）
                 */
                Map<String,String> params = new HashMap<>();
                params.put("elevatorIds",paperlessApply.getElevatorIds());
                params.put("isPaperlessMaintenance","0");
                elevatorMapp.updatePaperLessElevators(params);
            }
            users = partyMapp.queryUserList(map);

            if(!CollectionUtils.isEmpty(users)){
                for (String userId : users) {
                    String noticeTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
                    MessageNotice msg = new MessageNotice();
                    msg.setTitle(title);
                    msg.setContent(content);
                    msg.setReceiveUserId(userId);
                    msg.setIsRead("0");
                    msg.setNoticeTime(noticeTime);
                    msg.setReceivePartyId(paperlessApply.getJgPartyId());
                    messageNoticeMapp.add(msg);
                }
            }
        }
        catch (Exception e){
            logger.error("无纸化维保试点操作失败"+e.getMessage(), e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.returnError("操作失败，系统异常",null);
        }
        return ResultUtil.returnSuccess("操作成功",null);
    }

    @Override
    public Map<String, Object> delete(Map map) {
        try {
            if (map.get("ids") != null && !"".equals(map.get("ids"))) {
                for (Object id : (List) map.get("ids")) {
                    // 通过查询然后修改电梯台账
                    PaperlessMaintanceApply apply = paperlessMaintMapp.
                            queryById(id.toString());
                    List<String> list = Arrays.asList(apply.getElevatorIds().split(","));
                    if (list != null && list.size() > 0) {
                        for (String eid : list) {
                            Map<String, Object> mapList = new HashMap<>();
                            mapList.put("id", eid);
                            mapList.put("isPaperlessMaintenance", "0");
                            paperlessMaintMapp.updateIsPaperless(mapList);
                        }
                    }
                    paperlessMaintMapp.delete(id + "");
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            return ResultUtil.returnError("删除失败", null);
        }
        return ResultUtil.returnSuccess("删除成功", null);
    }

    /**
     * 无纸化维保试点申请
     * @param paperlessApply
     * @return
     */
    @Override
    public Map<String, Object> exportLetterOfCommitmentDoc(PaperlessMaintanceApply paperlessApply) {
        Map<String, Object> result = new HashMap<>();
        String path = environment.getProperty("upload", String.class);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateString = sdf.format(new Date());
        if (path.endsWith(File.separator)) {
            path = path + dateString + File.separator;
        } else {
            path = path + File.separator + dateString + File.separator;
        }
        File file1 = new File(path);
        if (!file1.exists()) {
            file1.mkdirs();
        }
        // 重现生成文件名，防止中文乱码
        String fileName = UUID.randomUUID() + ".docx";
        path = path + fileName;
        result.put("fileUrl", dateString + File.separator + fileName);

        if("1".equals(paperlessApply.getFlag())){
            result.put("fileName", "电梯无纸化维保试点工作承诺书.docx");
        }else{
            result.put("fileName", "电梯无纸化维保试点电梯列表.docx");
        }
        try{

            // 获取电梯数量
            Map<String,Object> map = new HashMap<>();
            map.put("jgPartyId",paperlessApply.getJgPartyId());
            map.put("maintenancePartyId",paperlessApply.getMaintenancePartyId());
            List<Map<String, Object>> areaElevatorList = paperlessMaintMapp.
                    paperlessGetAreaElevatorList(map);

            if("1".equals(paperlessApply.getFlag())){
                Map<String, String> data = new HashMap<>();

                String id = paperlessApply.getId().toString();
                data =  paperlessMaintMapp.getPaperLessInfo(id);
                data.put("totalList",String.valueOf(areaElevatorList.size()));

                XmlFill.poiExportNewWord(path,data,null,environment,"/paperlessLetterOfCommitment.docx");
            }else{
                Map<String, String> data = new HashMap<>();
                Map<String, Object> mapParams = new HashMap<>();
                List<String[]> elevatorList = new ArrayList<>();
                int i = 0;
                for (Map<String, Object> objectMap : areaElevatorList) {
                    String elevatorNum = objectMap.get("elevatorNum").toString();
                    String elevatorTypeName = objectMap.get("elevatorTypeName").toString();
                    String buildAddr = objectMap.get("buildAddr").toString();
                    String usedPartyName = objectMap.get("usedPartyName").toString();
                    elevatorList.add(new String[]{(i + 1) + "", elevatorNum, elevatorTypeName, buildAddr,usedPartyName});
                    if (i == 0) {
                        data.put("index", (i + 1) + "");
                        data.put("elevatorNum", elevatorNum != null ? elevatorNum : "");
                        data.put("elevatorTypeName", elevatorTypeName != null ? elevatorTypeName : "");
                        data.put("buildAddr", buildAddr != null ? buildAddr : "");
                        data.put("usedPartyName", usedPartyName != null ? usedPartyName : "");
                    }
                    i++;
                }
                mapParams.put("elevatorList", elevatorList);
                XmlFill.poiExportNewWord(path, data, null, environment, "/paperlessLetterOfEle.docx", mapParams);

            }
        } catch (Exception e) {
            logger.error("生成承诺书文件出现异常！", e);
        }
        return result;
    }

    /**
     * 获取无纸化维保可申请对象
     * @param extElevator
     * @return
     */
    @Override
    public Map<String, Object> getOptionalJgParty(ExtElevator extElevator) {
        List<Party> result = new ArrayList<>();
        try{
            result = paperlessMaintMapp.getOptionalParty(extElevator);
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            return ResultUtil.returnError("查询失败", null);
        }
        return ResultUtil.returnSuccess("成功",result);
    }

    /**
     * 获取维保单位电梯所在的区局
     * @param map
     * @return
     */
    @Override
    public Map<String, Object> paperlessGetApplicantList(Map map) {
        List<Map<String,Object>> result = new ArrayList<>();
        try{
            result = paperlessMaintMapp.paperlessGetApplicantList(map);
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            return ResultUtil.returnError("查询失败", null);
        }
        return ResultUtil.returnSuccess("成功",result);
    }

    /**
     * 开始核查申报条件
     * @param map
     * @return 1:是已经做过两次维保以上，0是未做过两次维保以上
     */
    @Override
    public Map<String, Object> paperlessStartCheck(Map map) {
        List<Map<String, Object>> result = new ArrayList<>();
        List<Map<String, Object>> nohasTwoList = new ArrayList<>();
        try {
            // 查询某区某维保单位所有的电梯列表
            List<Map<String, Object>> areaElevatorList = paperlessMaintMapp.
                    paperlessGetAreaElevatorList(map);

            // 返回值处理
            if (areaElevatorList == null) {
                return ResultUtil.returnSuccess("您公司下电梯台账为空，" +
                        "或者您单位下的电梯未关联所属分局", null);
            }
            // 获取已经做过两次维保的电梯
            List<String> areaTwoElevator = paperlessMaintMapp.
                    paperlessGetAreaTwoElevator(map);

            if (areaTwoElevator != null && areaTwoElevator.size() > 0) {
                // 满足的电梯，已经申报的去掉
                List<String> sureList = new ArrayList<>();
                for (Map<String, Object> param : areaElevatorList) {

                    String isPaperless = param.get("isPaperlessMaintenance").
                            toString();
                    // 已经申报了 或者 正在申报
                    if ("1".equals(isPaperless) || "2".equals(isPaperless)) {
                        continue;
                    }
                    // 满足条件
                    String elevatorNum = param.get("elevatorNum").toString();
                    if (areaTwoElevator.contains(elevatorNum)) {
                        String id = param.get("id").toString();
                        sureList.add(id);
                    } else {
                        // 不满足条件
                        param.put("isFlag", "0");
                        param.put("isMaint", "否");
                        // 将未做过两次维保的数据返回
                        nohasTwoList.add(param);
                    }
                }
                // 保存数据
                if (sureList != null && sureList.size() > 0) {
                    // 状态 0：未申请 1：已申请 2、申请中
                    map.put("applyDate", DateUtils.getDate("yyyy-MM-dd"));
                    map.put("applyStatus", "0");
                    map.put("elevatorIds", String.join(",", sureList));
                    paperlessMaintMapp.insertList(map);

                    for (String id : sureList) {
                        Map<String, Object> mapList = new HashMap<>();
                        mapList.put("id", id);
                        mapList.put("isPaperlessMaintenance", "2");
                        paperlessMaintMapp.updateIsPaperless(mapList);
                    }
                    if (nohasTwoList.size() > 0) {
                        return ResultUtil.returnSuccess("添加成功：" + sureList.size() + " 台，还有：" +
                                nohasTwoList.size() + " 台不满足条件，请查看详情,请耐心等待审批", nohasTwoList);
                    }
                    if (nohasTwoList == null) {
                       return ResultUtil.returnSuccess("添加成功，请耐心等待审批", result);
                    }
                } else if(nohasTwoList.size()>0) {
                    return ResultUtil.returnSuccess("贵公司在该区下已经没有满足做过两次以上维保的电梯,请查看未满足的电梯列表", nohasTwoList);
                }
            } else {
                return ResultUtil.returnSuccess("贵公司在该区下已经没有满足做过两次以上维保的电梯", null);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ResultUtil.returnError("查询失败", null);
        }
        return ResultUtil.returnSuccess("成功", result);
    }

    /**
     * 无纸化审核 监管单位
     * @param paperlessMaintanceApply
     * @return
     */
    @Override
    @Transactional
    public Map<String, Object> updateCheck(PaperlessMaintanceApply paperlessMaintanceApply) {
        try {
            String flag = "1";
            if (StringUtil.isNotBlank(paperlessMaintanceApply.getElevatorIds())) {
                // 先修改标志
                paperlessMaintMapp.updateCheckType(paperlessMaintanceApply);
                if (! "2".equals(paperlessMaintanceApply.getApplyStatus())) {
                    // 修改电梯标志
                    flag = "0";
                }
                List<String> ids = Arrays.asList(paperlessMaintanceApply.getElevatorIds().split(","));
                if (ids != null && ids.size() > 0) {
                    for (String id : ids) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("id", id);
                        map.put("isPaperlessMaintenance", flag);
                        paperlessMaintMapp.updateIsPaperless(map);
                    }
                } else {
                    return ResultUtil.returnError("电梯列表为空，请联系管理员", null);
                }


            } else {
                return ResultUtil.returnError("电梯列表为空，请联系管理员", null);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ResultUtil.returnError("审核失败" + e.getMessage(), null);
        }
        return ResultUtil.returnSuccess("审核成功", null);
    }
}
